package com.hundsun.yr.universal.p2p.ui.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.Utils.HeaderMap;
import com.hundsun.yr.universal.library.base.BaseWebActivity;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog;
import com.hundsun.yr.universal.library.widget.HSToast;
import com.hundsun.yr.universal.p2p.bean.AdSlideBeen;
import com.hundsun.yr.universal.p2p.bean.ListOfCashBean;
import com.hundsun.yr.universal.p2p.bean.MyInvestBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.Extras;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.InitializePresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseActivity;
import com.hundsun.yr.universal.p2p.ui.adapter.CashAdapter;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.view.base.BaseItemView;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 借款人提现页面
 * Created by Administrator on 2018/4/28.
 */

public class LendActivity extends BaseActivity implements BaseItemView,
        View.OnClickListener,
        HSDialog.HSDialogOnItemClickListener {

    private TextView lent_balance;
    private Spinner lent_project;
    private TextView lent_charge;
    private TextView lent_account;
    private Button lent_submission;
    private TextView lent_server;
    private EditText amount_of_cash_tv;
    private RequestPresenter mPresenter = null;
    private TextView TvlentFee;
    private String zwgt_data;
    private CashAdapter cashAdapter;
    private List<ListOfCashBean.ListBean> dataBeans = new ArrayList<>();
    private TextView amount_of_cash;
    private int position = 0;
    private ListOfCashBean bean;
    private LinearLayout layoutPro, layoutServerFee;
    private LinearLayout ly_tixian;
    private boolean state;
    /**
     * 重新签约
     *
     * @return
     */
    private HSDialog againSingDialog;
    public boolean isState = false;

    @Override
    protected boolean isApplyKitKatTranslucency() {

        return false;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        // TODO Auto-generated method stub
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.lend_layout;
    }

    @Override
    protected void initViewsAndEvents() {

        toolbar_title.setTextColor(Color.WHITE);
        toolbar_title.setText("提现");
        mToolbar.setNavigationIcon(R.drawable.icon_back);
        mToolbar.setBackgroundColor(Color.parseColor("#FA5B2C"));
        lent_balance = findView(R.id.lent_balance);
        lent_project = findView(R.id.lent_project);
        lent_charge = findView(R.id.lent_charge);
        lent_account = findView(R.id.lent_account);
        TvlentFee = findView(R.id.lent_fee);
        lent_server = findView(R.id.lent_server);
        lent_submission = findView(R.id.lent_submission);
        lent_submission.setOnClickListener(this);
        amount_of_cash_tv = findView(R.id.amount_of_cash_tv);
        mPresenter = new InitializePresenterImpl(mContext, this);
        amount_of_cash = findView(R.id.amount_of_cash);
        layoutPro = findView(R.id.layout_project);
        layoutServerFee = findView(R.id.layout_serverFee);
        ly_tixian = findView(R.id.ly_tixian);
//        if (state){
//            layoutServerFee.setVisibility(View.GONE);
//            layoutPro.setVisibility(View.GONE);
//            amount_of_cash.setVisibility(View.GONE);
//            amount_of_cash_tv.setVisibility(View.VISIBLE);
//            ly_tixian.setVisibility(View.GONE);
//        }
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        cashAdapter = new CashAdapter(mContext, dataBeans);

        lent_project.setAdapter(cashAdapter);
        /**
         * 设置项目服务费的显示和隐藏
         */
        lent_project.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                LendActivity.this.position = position;
                ListOfCashBean.ListBean dataBean = dataBeans.get(position);
                if (dataBean.getWithdraw().equals("")) {
                    return;
                }
                amount_of_cash_tv.setText(dataBean.getWithdraw());
                amount_of_cash_tv.setSelection(dataBean.getWithdraw().length());
                amount_of_cash.setText(dataBean.getWithdraw());
                /*lent_charge.setText(dataBean.getService_fee());
                lent_account.setText(String.valueOf(Double.valueOf(dataBean.getWithdraw()) - Double.valueOf(dataBean.getService_fee())));*/

                if (!dataBean.getLoan().equals("")) {
                    String serverFee = formatDouble3((Double.valueOf(dataBean.getWithdraw()) / Double.valueOf(dataBean.getLoan())) * Double.valueOf(dataBean.getService_fee()));
                    if (!bean.isProject()) {
                        lent_charge.setText("0");
                    } else {
                        lent_charge.setText(serverFee);
                    }

                    Double fee = Double.valueOf(dataBean.getWithdraw()) * Double.valueOf(bean.getCharge_rate());
                    if (fee < Double.valueOf(bean.getMin_charge())) {
                        fee = Double.valueOf(bean.getMin_charge());
                    }
                    if (!bean.isCharge()) {
                        fee = 0.00;
                    }
                    TvlentFee.setText(formatDouble3(fee));
                    lent_account.setText(formatDouble3(Double.valueOf(dataBean.getWithdraw()) - Double.valueOf(lent_charge.getText().toString().trim()) - Double.valueOf(TvlentFee.getText().toString().trim())));
                }

                if (dataBean.getService_fee().equals("0")) {
                    if (!bean.isProject()) {
                        lent_charge.setText("0");
                    } else {
                        lent_charge.setText(dataBean.getService_fee());
                    }

                    lent_account.setText(dataBean.getWithdraw());
                }

                if (dataBean.getWithdraw().equals("0")) {
                    lent_charge.setText("0");
                    TvlentFee.setText("0");
                    lent_account.setText("0");
                }

                if (dataBean.getName().equals("全部")) {
                    amount_of_cash.setVisibility(View.VISIBLE);
                    amount_of_cash_tv.setVisibility(View.GONE);
                    lent_balance.setText(dataBean.getWithdraw());
                    if (!bean.isProject()) {
                        lent_charge.setText("0");
                    } else {
                        lent_charge.setText(dataBean.getService_fee());
                    }

                    Double fee = Double.valueOf(dataBean.getWithdraw()) * Double.valueOf(bean.getCharge_rate());
                    if (fee < Double.valueOf(bean.getMin_charge())) {
                        fee = Double.valueOf(bean.getMin_charge());
                    }
                    if (!bean.isCharge()) {
                        fee = 0.00;
                    }
                    TvlentFee.setText(formatDouble3(fee));
                    if ((Double.valueOf(dataBean.getWithdraw()) - Double.valueOf(lent_charge.getText().toString()) - Double.valueOf(TvlentFee.getText().toString().trim()) < 0)) {
                        lent_account.setText("0");
                    } else {
                        lent_account.setText(formatDouble3(Double.valueOf(dataBean.getWithdraw()) - Double.valueOf(lent_charge.getText().toString().trim()) - Double.valueOf(TvlentFee.getText().toString().trim())));
                    }
                } else {
                    amount_of_cash.setVisibility(View.GONE);
                    amount_of_cash_tv.setVisibility(View.VISIBLE);
                }
                //项目无
                if (dataBean.getName().equals("无")) {
                    amount_of_cash.setVisibility(View.GONE);
                    amount_of_cash_tv.setVisibility(View.VISIBLE);
                    lent_balance.setText(dataBean.getWithdraw());
                    if (!bean.isProject()) {
                        lent_charge.setText("0");
                    } else {
                        lent_charge.setText(dataBean.getService_fee());
                    }

                    Double fee = Double.valueOf(dataBean.getWithdraw()) * Double.valueOf(bean.getCharge_rate());
                    if (fee < Double.valueOf(bean.getMin_charge())) {
                        fee = Double.valueOf(bean.getMin_charge());
                    }
                    if (!bean.isCharge()) {
                        fee = 0.00;
                    }
                    TvlentFee.setText(formatDouble3(fee));
                    lent_account.setText(formatDouble3(Double.valueOf(dataBean.getWithdraw()) - Double.valueOf(lent_charge.getText().toString().trim()) - Double.valueOf(TvlentFee.getText().toString().trim())));
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        amount_of_cash_tv.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                ListOfCashBean.ListBean dataBean = dataBeans.get(position);
                if (s.toString().equals(".")) {
                    amount_of_cash_tv.setText("");
                    return;
                } else if (s.toString().contains(".") && s.toString().split("[.]").length == 2 && s.toString().split("[.]")[1].length() > 2) {
                    String ss = formatDouble3(Double.valueOf(s.toString()));
                    amount_of_cash_tv.setText(ss);
                    amount_of_cash_tv.setSelection(ss.length());
                }
                String Withdraw = amount_of_cash_tv.getText().toString();
                if (Withdraw.equals("")) {
                    lent_charge.setText("0");
                    lent_account.setText("0");
                    return;
                } else if (Double.valueOf(Withdraw) > Double.valueOf(dataBean.getWithdraw())) {
                    Withdraw = dataBean.getWithdraw();
                    amount_of_cash_tv.setText(Withdraw);
                    amount_of_cash_tv.setSelection(Withdraw.length());
                } else if (!dataBean.getLoan().equals("")) {
                    String serverFee = formatDouble3((Double.valueOf(Withdraw) / Double.valueOf(dataBean.getLoan())) * Double.valueOf(dataBean.getService_fee()));
                    if (!bean.isProject()) {
                        lent_charge.setText("0");
                    } else {
                        lent_charge.setText(serverFee);
                    }

                    Double fee = Double.valueOf(amount_of_cash_tv.getText().toString().trim()) * Double.valueOf(bean.getCharge_rate());
                    if (fee < Double.valueOf(bean.getMin_charge())) {
                        fee = Double.valueOf(Double.valueOf(bean.getMin_charge()));
                    }
                    if (!bean.isCharge()) {
                        fee = 0.00;
                    }
                    TvlentFee.setText(formatDouble3(fee));

                    Double withdrawFee = Double.valueOf(amount_of_cash_tv.getText().toString().trim()) - Double.valueOf(lent_charge.getText().toString().trim()) - Double.valueOf(TvlentFee.getText().toString().trim());
                    if (withdrawFee < 0) {
                        withdrawFee = 0.0;
                    }

                    lent_account.setText(formatDouble3(withdrawFee));
                } else {
                    Double fee = Double.valueOf(amount_of_cash_tv.getText().toString().trim()) * Double.valueOf(bean.getCharge_rate());
                    if (fee < Double.valueOf(bean.getMin_charge())) {
                        fee = Double.valueOf(Double.valueOf(bean.getMin_charge()));
                    }
                    if (!bean.isCharge()) {
                        fee = 0.00;
                    }
                    TvlentFee.setText(formatDouble3(fee));
                    Double withdrawFee = Double.valueOf(amount_of_cash_tv.getText().toString().trim()) - Double.valueOf(TvlentFee.getText().toString().trim());
                    if (withdrawFee < 0) {
                        withdrawFee = 0.0;
                    }
                    lent_account.setText(formatDouble3(withdrawFee));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        // submission();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.loadingData(TaskConstants.TASK_WITHDRAEFEE, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.TASK_WITHDRAEFEE, Constants.EVENT_DATA,
                BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) + TaskConstants.TASK_WITHDRAEFEE, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.
                        getShareProf(UserInfo.TOKENID), zwgt_data), true);
    }


    @Override
    protected void onEveComming(EventCenter eventCenter) {

    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected View getLoadingTargetView() {
        return null;
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(R.id.common_toolbar).init();
    }

    //接口回调
    @Override
    public <T> void initializeViews(String task_name, T data) {
        switch (task_name) {
            case TaskConstants.TASK_CARDUNBIND:
                ListOfCashBean listOfCashBean = (ListOfCashBean) data;
                dataBeans.clear();
                updateUI(listOfCashBean);
                lent_balance.setText(listOfCashBean.getList().get(0).getWithdraw());
                dataBeans.addAll(listOfCashBean.getList());
                cashAdapter.notifyDataSetChanged();
                lent_project.setSelection(0);
                break;
            case TaskConstants.TASK_NEWWITHDRAW:
                Log.e("dd", String.valueOf(data));
                zwgt_data = BaseRequestTool2.getFormatedDateString();
                HashMap<String, String> hearder1 = BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, mContext.getString(R.string.h5_user) +
                        "withdrawrst", sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data);
                HeaderMap headerMap1 = new HeaderMap();
                headerMap1.setMap(hearder1);
                Bundle bundle1 = new Bundle();
                bundle1.putString(BaseWebActivity.BUNDLE_KEY_URL, String.valueOf(data));
                bundle1.putSerializable(BaseWebActivity.BUNDLE_KEY_HEADER, headerMap1);
                bundle1.putInt(BaseWebActivity.BUNDLE_KEY_LOADTYPE, BaseWebActivity.LoadType.DATA.getIntValue());
                readyGo(WebOpenAccountActivity.class, bundle1);
                break;
            case TaskConstants.TASK_SIGHJUST:
                AdSlideBeen been = (AdSlideBeen) data;
                againSingDialog = new HSDialog(getString(R.string.tips), been.getMsg(), "暂不签约",
                        "重新签约", mContext, this).setCancelable(false);
                againSingDialog.show();
                break;
        }

    }

    /**
     * 更新数据
     *
     * @param listOfCashBean
     */
    private void updateUI(ListOfCashBean listOfCashBean) {
        bean = listOfCashBean;
        if (!bean.isProject()) {
//            layoutServerFee.setVisibility(View.GONE);
//            layoutPro.setVisibility(View.GONE);
//            amount_of_cash.setVisibility(View.GONE);
//            amount_of_cash_tv.setVisibility(View.VISIBLE);
            lent_balance.setText(listOfCashBean.getList().get(0).getWithdraw());
        }
        if (!bean.isCharge()) {
//            ly_tixian.setVisibility(View.GONE);
        }

    }

    @Override
    public <T> void initializeError(String task_name, T data) {

    }

    @Override
    public <T> void setAdapter(List<T> data) {

    }

    private void submission() {
        String zwgt_data = BaseRequestTool2.getFormatedDateString();
        JSONObject map = new JSONObject();
        String lentCharge, chargeFee;
        if (!bean.isProject()) {
            lentCharge = "0";
        } else {
            lentCharge = lent_charge.getText().toString();
        }
        if (!bean.isCharge()) {
            chargeFee = "0";
        } else {
            chargeFee = TvlentFee.getText().toString().trim();
        }
        try {
            map.put("amount", lent_account.getText().toString());
            map.put("txfee", lentCharge);
            map.put("uuid", dataBeans.get(position).getUuid());
            map.put("charge", chargeFee);
            map.put("total_amount", amount_of_cash_tv.getText().toString().trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
        mPresenter.loadingData(TaskConstants.TASK_NEWWITHDRAW, getString(R.string.root_url_test) + getString(R.string.api_trade_test) + TaskConstants.TASK_NEWWITHDRAW,
                Constants.EVENT_DATA, jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, getString(R.string.api_trade_test) + TaskConstants.TASK_NEWWITHDRAW,
                        sharedPreferences.getShareProf(UserInfo.USER_NO),
                        sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
    }

    public static String formatDouble3(double value) {
        DecimalFormat formater = new DecimalFormat();
        formater.setMaximumFractionDigits(2);
        formater.setGroupingSize(0);
        formater.setRoundingMode(RoundingMode.FLOOR);
        return formater.format(value).replace(",", "");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lent_submission:
                if (!lent_account.getText().toString().equals("0")) {
                    /**
                     * 提现前判断
                     */

                    if (amount_of_cash_tv.getText().toString().trim().equals("")) {
                        new HSToast(mContext).showCustomToast("提现金额不能为空");
                    } else if (Double.valueOf(amount_of_cash_tv.getText().toString().trim()) < Double.valueOf(bean.getMin().trim().trim())) {
                        new HSToast(mContext).showCustomToast("最小金额为" + bean.getMin());
                    } else if (Double.valueOf(amount_of_cash_tv.getText().toString().trim()) > Double.valueOf(bean.getMax().trim().trim())) {
                        new HSToast(mContext).showCustomToast("最大金额为" + bean.getMax());
                    } else if (Double.valueOf(lent_balance.getText().toString().trim()) < Double.valueOf(bean.getMin())) {
                        showToast("账户余额不足");
                    } else {
                        submission();
                    }
                } else {
                    new HSToast(mContext).showCustomToast("金额不能为零");
                }
                break;
        }
    }

    @Override
    public void onItemClick(Object o, int position) {
        //重新签约
        if (o == againSingDialog && position != -1) {
            readyGo(ManagementActivity.class);
        }
    }
}
